# -*- coding: utf-8 -*-
import logging
import time
from traceback import format_exc
from pymongo import UpdateOne
from zc_core.client.mongo_client import Mongo
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.encrypt_util import md5


class SimpleDao(object):
    db_name_tpl = 'ctaxccgp_{}'

    def get_batch_data(self, batch_no):
        if batch_no:
            try:
                year = str(batch_no)[:-4]
                db = Mongo().client[self.db_name_tpl.format(year)]
                ids = db['data_{}'.format(batch_no)].find({}, {'_id': 1})
                return list(ids)
            except Exception as ex:
                logging.info('work exception: %s' % format_exc())
                time.sleep(15)
        return []

    def save_orders(self, order_list):
        if order_list:
            try:
                year_bulk_map = dict()
                for data in order_list:
                    order_dept = data.get('orderDept')
                    if order_dept and not data.get('deptId'):
                        data['deptId'] = md5(order_dept)
                    # 计算批次编号
                    batch_no = data.get('batchNo')
                    if not batch_no and data.get('orderTime', None):
                        # 要求: 本地时间(东八区)
                        order_time = data.get('orderTime', '')
                        if order_time:
                            batch_no = time_to_batch_no(order_time)
                            data['batchNo'] = batch_no
                    if batch_no:
                        year = str(batch_no)[:-4]
                        bulk_list = year_bulk_map.get(year, [])
                        bulk_list.append(UpdateOne({'_id': data['_id']}, {'$set': data}, upsert=True))
                        year_bulk_map[year] = bulk_list
                for year, bulk_list in year_bulk_map.items():
                    db = Mongo().client[self.db_name_tpl.format(year)]
                    db['order_{}'.format(year)].bulk_write(bulk_list, ordered=False, bypass_document_validation=True)
            except Exception as ex:
                logging.info('work exception: %s' % format_exc())
                time.sleep(15)
                # 重试
                logging.info('--> retry save_orders: page=%s' % order_list)
                self.save_orders(order_list)
